<template>
  <div v-if="dataInfo" class="c-p c-pt72 c-flex-column">
    <img class="c-w100 c-hh358 c-pa c-p-t0 c-p-l0 c-pz-1" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/present/present_couse_bg_top.png" alt="" />
    <img :src="dataInfo.headimgurl || require('@/assets/defult_head.png')" class="c-ww120 c-hh120 c-bd4-white c-brp50 c-mlr-auto" alt="" />
    <div class="c-flex-row c-flex-center c-mt20 c-fs24">
      <span>来自「</span>
      <span class="c-maxw300 c-text-ellipsis1">{{ dataInfo.nickname }}</span>
      <span>」的赠送</span>
    </div>
    <!-- 产品信息介绍 -->
    <article class="c-ml22 c-mt26 c-ww596 c-hh620 c-ph38 c-pt6 c-p">
      <img class="c-w100 c-h c-pa c-p-t0 c-p-l0 c-pz-1" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/present/present_couse_bg_content.png" alt="" />
      <div class="c-hh100 c-flex-row c-flex-center c-fs26 c-fc-white c-ph20">
        <span class="c-wb-ba c-lh36 c-text-ellipsis2 c-textAlign-c">赠言：{{ presentMsg }}</span>
      </div>
      <div class="c-mt20 c-w100 c-hh346 c-p" @click="tapGoProdDetail">
        <CoverImg :prodType="presentProdType" coverSizeClass="c-w100 c-h c-text-hidden c-br16" imgClass="c-br16" :coverUrl="$addXossFilter(dataInfo.avatar)" />
        <div class="c-br8 c-hh28 c-lh30 c-ph6 c-textAlign-c c-translucent-balck60 c-fs18 c-fc-white c-pa c-p-b8 c-p-r8 c-pz9">
          {{ presentProdType == cfrom.course ? COURSE_TYPE_MAP[dataInfo.courseType] : PROD_TYPE_MAP[dataInfo.prodType] }}
        </div>
      </div>
      <div class="c-mt20 c-fs26 c-fw-b c-text-ellipsis2">{{ dataInfo.prodName }}</div>
      <div class="c-flex-row c-aligni-center c-mt10 c-fs24 c-fw-b">
        <span class="c-fc-xmlred" v-if="dataInfo.prodPrice * 1 != 0">{{ '￥' | iosPriceFilter }}{{ dataInfo.prodPrice }}</span>
        <span class="c-fc-sblack c-ml-auto">x1</span>
      </div>
    </article>
    <!-- 赠送领取按钮 -->
    <div @click="tapPresent" class="c-mt30 c-ww500 c-hh76 c-flex-row c-flex-center c-fc-white c-fs28 c-br40 c-mlr-auto c-fw-b" :class="isCanSend ? 'sent-btn-bg' : 'c-bg-dd'">{{ getSentText }}</div>
    <section v-if="isShowEditMsg || isShowNextPresent" class="c-flex-row c-flex-center c-mt20 c-fs24 c-fc-gray">
      <span v-if="isShowEditMsg" @click="tapOpenEditMsg" class="c-bd-b1-ccc c-mr40">编辑赠言</span>
      <span v-if="isShowNextPresent" @click="tapNextPresent" class="c-bd-b1-ccc">下次赠送</span>
    </section>
    <section v-if="isShowQrcode" class="c-flex-column c-aligni-center c-mt40">
      <div class="c-p c-mt30 c-ww200 c-hh200">
        <div class="iconfont c-pa c-p-l0 c-p-t0 c-rotate180 c-fc-xmlred">&#xe865;</div>
        <div class="iconfont c-pa c-p-r0 c-p-t0 c-rotate270 c-fc-xmlred">&#xe865;</div>
        <div class="iconfont c-pa c-p-b0 c-p-l0 c-rotate90 c-fc-xmlred">&#xe865;</div>
        <div class="iconfont c-pa c-p-b0 c-p-r0 c-fc-xmlred">&#xe865;</div>
        <img class="c-w100 c-h" :src="$addXossFilter(dataInfo.mpQrcode)" />
      </div>
      <div class="c-mt30 c-fs24">为了让您更好地学习，请长按二维码关注公众号</div>
    </section>
    <section v-if="recievers.length" class="c-mt60 receive-list-bg c-flex-column c-ph24 c-pb50 c-fs24">
      <div class="c-pt20 c-fw-b receive-title-bg c-mlr-auto">领取记录</div>
      <div v-for="(item, index) in recievers" :key="index" class="c-flex-row c-aligni-center c-pt40 ">
        <img class="c-ww64 c-hh64 c-brp50" :src="item.avatar || require('@/assets/defult_head.png')" alt="" />
        <div class="c-ph20 c-flex-grow1 c-w0 c-flex-column">
          <span class="c-text-ellipsis1 c-fw-b">{{ item.nickname }}</span>
          <span class="c-fc-gray c-mt10">{{ item.createdAt }}</span>
        </div>
        <div>领取了赠送</div>
      </div>
    </section>
    <share-masker :isShowShare="isShowShare" v-if="isShowShare" @closeShare="isShowShare = false"></share-masker>
    <edit-present-msg v-if="memberFrom == 2" ref="editPresentMsgRef" @confirmPresentMsg="handerConfirmPresentMsg" />
    <!-- 显示购买赠送积分 -->
    <point-gift v-if="memberFrom == 2" :showPoints.sync="showPoints" :prodId="dataInfo.prodId" :rewardPoints="rewardPoints"></point-gift>
  </div>
</template>
<script>
import CoverImg from '@/components/templates/common/coverImg.vue';
import shareMasker from '@/components/templates/common/shareMasker.vue';
import pointGift from '@/components/templates/common/pointGift.vue';
import editPresentMsg from '@/components/templates/common/editPresentMsg.vue';
import { utilJs } from '@/utils/common.js';
import { PROD_TYPE_MAP, DEFAULT_IMG_MAP, LOAD_STATUS_ENUM } from '@/utils/constant.js';
import { goDetails } from '@/utils/goDetails.js';
import { getBindPhoneSetting } from '@/utils/checkUnBindPhone.js';
const LIMIT = 10;
export default {
  name: 'PresentCourse',
  components: {
    shareMasker,
    pointGift,
    editPresentMsg,
    CoverImg
  },
  props: [],
  beforeCreate() {},
  data() {
    return {
      COURSE_TYPE_MAP: global.prodCourseType,
      PROD_TYPE_MAP: PROD_TYPE_MAP,
      customPointName: localStorage.getItem('customPointName'),
      cfrom: global.ckFrom,
      isShowShare: false,
      companyAuth: JSON.parse(localStorage.getItem('companyAuth')),
      uId: localStorage.getItem('userId'),
      dataInfo: null,
      presentMsg: '',
      memberFrom: 0, //1是代理商赠送会员，2是普通课程赠送，3.股东赠送
      recievers: [],
      LOAD_STATUS_ENUM: LOAD_STATUS_ENUM,
      loadingStatus: LOAD_STATUS_ENUM.NO_MORE_DATA, //显示加载更多LOAD_MORE 加载中 LOADING 没有更多 NO_MORE_DATA
      showPoints: false,
      rewardPoints: 0,
      sUserId: '' //赠送股东的userId
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {
    presentProdType() {
      // 赠送产品类型转化成原产品类型
      if (!this.dataInfo) {
        return;
      }
      if (this.dataInfo.prodType == global.ckFrom.presentCourse) {
        return global.ckFrom.course;
      }
      if (this.dataInfo.prodType == global.ckFrom.presentColumn) {
        return global.ckFrom.column;
      }
      if (this.dataInfo.prodType == global.ckFrom.presentPackage) {
        return global.ckFrom.package;
      }
      return this.dataInfo.prodType;
    },
    isShowEditMsg() {
      if (!this.dataInfo) {
        return;
      }
      // 赠送课程才有赠言编辑，其他没有
      return this.memberFrom == 2 && this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId == 0;
    },
    isShowNextPresent() {
      //是否显示下次赠送
      if (!this.dataInfo) {
        return false;
      }
      const isCanCourseSent = this.memberFrom == 2 && this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId == 0;
      const isCanShareholderSent = this.memberFrom == 3 && this.uId == this.dataInfo.userId;
      const isCanAgentSent = this.memberFrom == 1 && this.dataInfo.loginUserId == this.dataInfo.userId;
      return isCanCourseSent || isCanShareholderSent || isCanAgentSent;
    },
    // 获取赠送/领取按钮文案信息
    getSentText() {
      if (!this.dataInfo) {
        return '';
      }
      //服务商赠送
      if (this.memberFrom == 1) {
        return this.dataInfo.btnMsg;
      }
      //赠送课程
      if (this.memberFrom == 2) {
        let text = '';
        if (this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId == 0) {
          text = '赠送好友';
        } else if (this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.shareId == 0 && !this.dataInfo.hasPermission) {
          text = '领取';
        } else if (this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.shareId == 0 && this.dataInfo.hasPermission) {
          text = '您已经有相关权限，不需再领取啦！';
        } else if (this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.shareId == this.dataInfo.loginUserId) {
          text = '您已领取啦！';
        } else {
          text = '已被领取';
        }
        return text;
      }
      //代理商赠送
      if (this.memberFrom == 3) {
        const text = this.uId == this.dataInfo.userId ? '赠送好友' : this.dataInfo.msg;
        return text || '领取';
      }
      return '';
    },
    isCanSend() {
      if (!this.dataInfo) {
        return false;
      }
      //代理商是否可赠送/领取
      if (this.memberFrom == 1) {
        return this.dataInfo.btnSt >= 0;
      }
      // 赠送课程是否可赠送/领取
      if (this.memberFrom == 2) {
        const isMeSent = this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId == 0;
        const isCanGet = this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.shareId == 0 && !this.dataInfo.hasPermission;
        return isMeSent || isCanGet;
      }
      // 股东是否可赠送/领取
      if (this.memberFrom == 3) {
        return !this.dataInfo.msg && this.dataInfo.leftNum > 0;
      }
      return false;
    },
    isShowQrcode() {
      // 赠送课程才显示二维码
      if (!this.dataInfo) {
        return false;
      }
      if (this.memberFrom == 2 || this.memberFrom == 1) {
        return this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.mpQrcode
      }
      return false;
    }
  },
  methods: {
    /**
     * 打开编辑赠言弹窗
     */
    tapOpenEditMsg() {
      this.$refs.editPresentMsgRef.pubilc_openEditMsg(this.presentMsg);
    },
    /**
     * 确认修改赠言
     * @param msg
     */
    handerConfirmPresentMsg(msg) {
      this.presentMsg = msg;
      this.savePresentMsg();
    },
    /**
     * 下次赠送
     */
    tapNextPresent() {
      //赠送课程
      if (this.memberFrom == 2) {
        this.$routerGo(this, 'replace', { path: '/member/presentCourse/presentCourseList' });
        return;
      }
      //股东赠送约课
      if (this.memberFrom == 3) {
        utilJs.postMethod(global.apiurl + 'shareholder/cancelPresentEquity', { id: this.dataInfo.id }, () => {
          this.$router.go(-1);
        });
        return;
      }
      this.$router.go(-1);
    },
    /**
     * 点击赠送/领取
     */
    tapPresent() {
      if (this.memberFrom == 3) {
        this.presentShareholder();
        return;
      }
      if (this.memberFrom == 2) {
        this.presentCourse();
        return;
      }
      if (this.memberFrom == 1) {
        this.presentAgent();
        return;
      }
    },
    /**
     * 股东赠送/领取
     */
    presentShareholder() {
      //不可赠送领取
      if (!this.isCanSend) {
        return;
      }
      //当前是分享人
      if (this.uId == this.dataInfo.userId) {
        this.isShowShare = true;
        return;
      }
      //当前是领取人
      if (this._bindPhoneSetting && this._bindPhoneSetting.getBind && utilJs.goBindMobile()) {
        return;
      }
      let datas = { sUserId: this.sUserId, id: this._presentId };
      utilJs.postMethod(`${global.apiurl}shareholder/userCollectEquity`, datas, res => {
        if (res.status) {
          this.dataInfo.msg = res.msg;
        }
        this.$showCjToast({
          text: res.status ? '领取成功' : res.msg,
          type: res.status ? 'success' : 'warn',
        }).then(() => {
          this.tapGoProdDetail();
        });
      });
    },
    /**
     * 课程赠送/领取
     */
    presentCourse() {
      if (this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId == 0) {
        this.isShowShare = true;
        return;
      }
      if (this.dataInfo.loginUserId != this.dataInfo.userId && this.dataInfo.shareId == 0 && !this.dataInfo.hasPermission) {
        let datas = {
          orderId: this.dataInfo.orderId,
          shareId: this.dataInfo.loginUserId,
          shareMsg: this.dataInfo.shareMsg
        };
        if (this._fromShare == 1) {
          datas.fromShare = 1;
        }
        this.getPresent(datas);
      }
    },
    /**
     * 代理商赠送/领取
     */
    presentAgent() {
      //不可赠送领取
      if (!this.isCanSend) {
        return;
      }
      //当前是分享人
      if (this.dataInfo.loginUserId == this.dataInfo.userId) {
        this.isShowShare = true;
        return;
      }
      //当是领取人点领取
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;
      let datas = {
        type: this.dataInfo.type
      };
      utilJs.postMethod(
        global.apiurl + 'members/receivePresent/' + this._presentId,
        datas,
        res => {
          this._isLoading = false;
          const recieveStatus = res.status;
          this.dataInfo.btnMsg = res.msg;
          //status = -1， msg = 匿名用户无法领取 OR 请先绑定手机号码，再领取等新增的提示都是-1
          // status = -2， msg =您来晚一步，已经被领取完了
          // status = -2， msg =您来晚一步，已经过期了 OR 赠送已过期
          // status = 1， msg = 网络拥堵，正在排队领取
          // status = 2， msg = 领取成
          this.dataInfo.btnSt = res.status;
          if (recieveStatus == 1) {
            this.$showCjToast({
              text: '正在排队领取',
              type: 'warn'
            });
            return;
          }
          if (recieveStatus == -1) {
            this.$showCjToast({
              text: '请先绑定手机号再领取',
              type: 'warn'
            }).then(() => {
              utilJs.goBindMobile();
            });
            return;
          }
          if (recieveStatus == 2) {
            this.$showCjToast({
              text: '领取成功',
              type: 'success',
            });
            this.dataInfo.btnSt = -1;
            this._page = 1;
            this.recievers = [];
            this.presentDetailAgent();
          }
        },
        () => {
          this._isLoading = false;
        }
      );
    },
    //课程 领取赠送/修改赠言
    getPresent(datas) {
      if (this._isLoading) {
        return;
      }
      this._isLoading = true;
      let shareId = datas.shareId;
      utilJs.postMethod(
        `${global.apiurl}orders/shareToFriend`,
        datas,
        () => {
          this._isLoading = false;
          if (shareId != 0) {
            this.$showCjToast({
              text: '领取成功',
              type: 'success',
            }).then(() => {
              this.tapGoProdDetail();
            });
          }
        },
        () => {
          this._isLoading = false;
        }
      );
    },
    /**
     * 分享成功保存赠送文案
     */
    savePresentMsg() {
      if (this.memberFrom != 2) {
        return;
      }
      let datas = {
        orderId: this.dataInfo.orderId,
        shareId: 0,
        shareMsg: this.presentMsg
      };
      this.getPresent(datas);
      this.initShareInfo();
    },
    //跳转对应详情页
    tapGoProdDetail() {
      let query = {
        ckFrom: this.presentProdType
      };
      goDetails(this, this.dataInfo.prodType, this.dataInfo.prodId, query, this.dataInfo.courseType);
    },
    //股东赠送
    shPresentDetail() {
      let urlT = global.apiurl + 'shareholder/userCollectEquityPage?id=' + this._presentId + '&sUserId=' + this.sUserId;
      utilJs.getMethod(urlT, res => {
        if (!res) {
          return;
        }
        res.avatar = res.avatar || DEFAULT_IMG_MAP[res.prodType];
        res.nickname = res.sName;
        this.dataInfo = res;
        this.presentMsg = res.desc;
        this.initShareInfo();
      });
    },
    //获取课程赠送详情
    presentDetail() {
      let getUrl = `${global.apiurl}orders/orderShare/${this._orderId}`;
      if (this._fromShare == 1) {
        getUrl = `${getUrl}?fromShare=1`
      }
      utilJs.getMethod(getUrl, res => {
        if (!res) {
          return;
        }
        res.avatar = this.getCourseAvatar(res);
        this.dataInfo = res;
        var rewardPoints = sessionStorage.getItem(res.prodId + 'rewardPoints');
        var rewardPoints1 = sessionStorage.getItem(this._orderId + 'rewardPoints');
        if (rewardPoints > 0 || rewardPoints1 > 0) {
          this.showPoints = true;
          this.rewardPoints = rewardPoints > 0 ? rewardPoints : rewardPoints1;
        }
        this.presentMsg = this.dataInfo.shareMsg || '您的好友大赠送啦，快快领取吧！';
        //当前是分享人，并且已经被领取了
        if (this.dataInfo.loginUserId == this.dataInfo.userId && this.dataInfo.shareId != 0) {
          this.recievers = [{
            avatar: this.dataInfo.shareimgurl,
            nickname: this.dataInfo.shareName,
            createdAt: this.dataInfo.time
          }]
          this.loadingStatus = LOAD_STATUS_ENUM.NO_MORE_DATA;
        }
        this.initShareInfo();
      });
    },
    getCourseAvatar(res) {
       //vip自定义封面
       if (res.vipInfo && res.vipInfo.cover && res.vipInfo.cover.coverType == 2) {
        return res.vipInfo.cover.coverUrl;
      }
      return res.avatar || DEFAULT_IMG_MAP[res.prodType];
    },
    /**
     * 代理商赠送详情
     */
    presentDetailAgent() {
      if (this.loadingStatus == LOAD_STATUS_ENUM.LOADING) {
        return;
      }
      this.loadingStatus = LOAD_STATUS_ENUM.LOADING;
      utilJs.getMethod(`${global.apiurl}members/presents/${this._presentId}?page=${this._page}&limit=${LIMIT}`, res => {

        if (this._page == 1 && !this.dataInfo) {
          const prodType = this.getAgentVipType(res);
          const avatar = this.getAgentAvatar(res);
          this.dataInfo = {
            ...res,
            mpQrcode: res.companyQrcode && res.companyQrcode.mpQrcode,
            avatar: avatar,
            prodType: prodType
          };
          console.log('--data-', this.dataInfo);
          const defaultMsg = prodType == global.ckFrom.vip ? '领取后，可免费享受VIP权益！快来领取吧！' : '领取后，可免费享受SVIP权益！快来领取吧！';
          this.presentMsg = this.dataInfo.desc || defaultMsg;
          this.initShareInfo();
        }
        let resList = res.arrPre.data || [];
        const { list, loadStatus, page } = utilJs.formatListData(this._page, LIMIT, resList, this.recievers);
        this.recievers = list;
        this.loadingStatus = loadStatus;
        this._page = page;
      });
    },
    getAgentVipType(res) {
        if (res.vipInfo && res.vipInfo.vipType == 2) {
          return global.ckFrom.vip;
        }
        return global.ckFrom.svip;
    },
    getAgentAvatar(res) {
      //vip自定义封面
      if (res.vipInfo && res.vipInfo.cover && res.vipInfo.cover.coverType == 2) {
        return res.vipInfo.cover.coverUrl;
      }
      if (res.vipInfo && res.vipInfo.vipType == 2) {
        const vipCover = require('@/assets/i/wap/course/vip.png');
        return vipCover;
      }
      const svipCover = require('@/assets/i/wap/course/svip.png');
      return svipCover;
    },
    initShareInfo() {
      const refereeId = this.memberFrom == 1 ? this.dataInfo.rUserId : this.uId;
      this._shareInfo = {
        title: this.dataInfo.prodName,
        desc: this.presentMsg || '知识改变命运，每天进步一点点！快来一起学习吧！',
        imgUrl: this.dataInfo.avatar,
        link: window.location.href.split('#')[0] + '#' + this.$route.fullPath + '&refereeId=' + refereeId
      };
      this.wechatShare();
    },
    //分享
    wechatShare: function() {
      utilJs.wechatConfig(this._shareInfo.link, this._shareInfo.title, this._shareInfo.imgUrl, this._shareInfo.desc);
    },
    //手机端分享
    appShare: function() {
      utilJs.appShareTrue(this._shareInfo.title, this._shareInfo.imgUrl, this._shareInfo.link, this._shareInfo.desc);
    },
    //下拉加载更多
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.loadingStatus == LOAD_STATUS_ENUM.HAS_MORE_DATA && this.recievers.length) {
          this.presentDetailAgent();
        }
      });
    }
  },
  mounted() {
    //赠送课程，专栏，知识套餐,vip/svip
    setDocumentTitle('赠送好友');
    this._isLoading = false;
    this._page = 1;
    this._fromShare = this.$route.query.fromShare || '';
    const memberFrom = this.$route.query.memberFrom || 2; //1：代理商赠送会员,2是正常课程赠送，3是股东赠送
    this.memberFrom = memberFrom == 'agent' ? 1 : memberFrom;
    getBindPhoneSetting(3).then(res => {
      this._bindPhoneSetting = res;
    });
    //代理商赠送会员
    if (this.memberFrom == 1) {
      this._presentId = this.$route.query.presentId;
      this.presentDetailAgent();
      window.addEventListener('scroll', this.windowScrollFunction);
      return;
    }
    //正常课程赠送
    if (this.memberFrom == 2) {
      this._orderId = this.$route.query.orderId || -1;
      this.presentDetail();
      return;
    }
    //股东赠送
    if (this.memberFrom == 3) {
      this._presentId = this.$route.query.id;
      this.sUserId = this.$route.query.sUserId;
      this.shPresentDetail();
      return;
    }
  },
  beforeDestroy() {
    sessionStorage.removeItem(this.dataInfo.prodId + 'rewardPoints');
    if (this.memberFrom == 1) {
      window.removeEventListener('scroll', this.windowScrollFunction);
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.sent-btn-bg {
  background-image: linear-gradient(179deg, #ff876b 0%, #fd2d49 100%);
}
.receive-list-bg {
  background-image: linear-gradient(to bottom, rgba(255, 48, 12, 0.08) 0%, rgba(255, 48, 12, 0) 50%, rgba(255, 48, 12, 0) 100%);
  background-size: 100%;
  background-repeat: no-repeat;
  border-radius: 0.9rem 0.9rem 0 0;
}
.receive-title-bg {
  position: relative;
  width: fit-content;
}
.receive-title-bg::after {
  content: '';
  position: absolute;
  bottom: -0.15rem;
  left: 0;
  right: 0;
  height: 0.3rem;
  background-image: linear-gradient(270deg, rgba(253, 45, 73, 0) 0%, #fd2d49 100%);
  z-index: -1;
}
</style>
